﻿using UnityEngine;
using System.Collections;
using System.Threading;
using Tools;
using Common;
namespace Sockets
{
    /// <summary>
    /// 数据包缓存管理,进队列优先
    /// </summary>
    public class MessageCache : IPackageCache
    {

        /// <summary>
        /// 存储socket 接受到的字节流数据
        /// </summary>
        private SafeQueue<IProtocol> PackageCache = new SafeQueue<IProtocol>();


        /// <summary>
        /// 记录数据包是否正在进队列。
        /// </summary>
        static  long   flag = 0;
        /// <summary>
        /// 数据包个数
        /// </summary>
        private int count = 0;

        /// <summary>
        /// 队列中是否有数据。如果数据正在进队列。则返回false
        /// </summary>
        public   bool Havedata
        {
            get
            {
                if (IsEnqueue) return false;
                if (PackageCache == null) return false;
            //   count = PackageCache.Count;
                return count > 0;
            }

        }


        public  void OnPushPackage(IProtocol package)
        {

            AddPackage(package);
        }



        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="package"></param>
        private void AddPackage(IProtocol package)
        {
            if (PackageCache == null)
            {
                 Logger.ErrorInfo("PackageCache is Destroyed", "MessageCache", "AddPackage");
                return;
            }
            try
            {
                //进队列，信号量+1
                Interlocked.Increment(ref flag);
                PackageCache.Enqueue(package);
                count++;
            }
            catch (System.Exception e)
            {
                Debug.Log(e.Message + "\n\n" + e.StackTrace);
            }
            finally
            {
                ///进队列完成，信号量-1；
                Interlocked.Decrement(ref flag);
            }
        }


        /// <summary>
        /// 获取一个数据包
        /// </summary>
        /// <returns></returns>
        public   IProtocol GetPackage()
        {
            if (IsEnqueue) return null;
            if (count < 1) return null;

            count--;
            return PackageCache.Dequeue();

        }



        bool IsEnqueue
        {
            get
            {
                return flag > 0;
            }

        }




        /// <summary>
        /// 销毁方法
        /// </summary>
        public  void DestroySelf()
        {
            
            if (PackageCache != null)
                PackageCache.Clear();
           
            PackageCache = null;
        }


    }

}